/**
 * 处理情况统计(企业)
 */
var iFrameName = this.name;
var enterpriseProcessingStatistics = {
		init: function(){
			var me = this;
			me.initEvent();
			me.loadTableTitle();
			me.initEmptyVehicleList();
			me.initQueryTime();
			me.BarChart=this.initBarChart();
			me.PieChart=this.initPieChart();
			me.LineChart=this.initLineChart();
			me.initProcessingStatistics();
		},
		initEvent: function(){
			var me = this;
			 $('#queryBtn').click(function () {
				 me.initProcessingStatistics();
				 //me.queryLineListByHandleName();
				 //me.queryTable();
		     });
			 
			 $('#exportExcel').click(function () {
				 me.exportEnterprise();
			 });
			 
			 $('#confirmExport').click(function () {
				 me.exportComfirm();
			 });
			 
			 $.ajax({
		    		type : 'post',
		    		async : true,
		    		url : appCtx+"base/report/enterpriseProcessingStatistics/queryAllAlarmType.html",
		    		cache : false,
		    		dataType : "JSON",
		    		success : function(data) {	
		    			if(data){
		    				var selectStr="<option value ='' selected='selected'>请选择报警类型 </option>";
		    				for(var i=0;i<data.length;i++){
		    					selectStr+="<option value='"+data[i].id+"'>"+data[i].name+"</option>";
		    				}
		    				$('#alarmTypeSelect').html(selectStr);
		    			}
		    		}
			 });
		},
		
		loadTableTitle:function(){
	    	$("#resultTable").flexigrid({
		            dataType : 'json',
		            colModel :[{
		                display : '车牌号',
		                name : 'vehicle_no',
		                width : 15,
		                sortable : false,
		                align : 'left'
		            },{
		                display : '报警类型',
		                name : 'alarm_name',
		                width : 17,
		                sortable : false,
		                align : 'left',
		                showTitle : 'alarm_name'
		            },{
		                display : '报警来源',
		                name : 'alarm_src',
		                width : 10,
		                sortable : false,
		                align : 'left',
		                showTitle : 'alarm_src',
		                paramcolnames:['alarm_src'],
		                handlefunction:function(alarm_src){
		                	var handleStr =alarm_src==1?'终端':'平台';	
		            		return handleStr;
		                }
		            },{
		                display : '报警时间',
		                name : 'alarm_time',
		                width : 20,
		                sortable : false,
		                align : 'left',
		                paramcolnames:['alarm_time'],
		                handlefunction:enterpriseProcessingStatistics.getFormatTime
		            },{
		                display : '处理类型',
		                name : 'handle_type',
		                width : 10,
		                sortable : false,
		                align : 'left',
		                paramcolnames:['handle_type'],
		                handlefunction:function(handle_type){
		                	var handleStr =handle_type==1?'系统处理':'人工处理';	
		            		return handleStr;
		                }
		            },{
		                display : '处理时间',
		                name : 'handle_time',
		                width : 20,
		                sortable : false,
		                align : 'left',
		                paramcolnames:['handle_time'],
		                handlefunction:enterpriseProcessingStatistics.getFormatTime
		            },{
		                display : '处理内容',
		                name : 'handle_remark',
		                width : 15,
		                sortable : false,
		                align : 'left',
		                showTitle : 'handle_remark'
		            }] ,
		            resizable : false,
					sortname : "id",// 第一次加载数据时排序列
					sortorder : "desc",// 第一次加载数据时排序类型
					usepager : true,// 是否分页，默认为true。
					showToggleBtn : false,
					showTableToggleBtn : true,// 是否显示收起/打开按钮,默认不显示。
					useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
					rp : 10,// 每页记录数，默认为10
					checkbox : false,// 是否要多选框,默认为false。
					rowId : 'id',// 多选框绑定行的id,只有checkbox : true时才有效。
					singleSelect : false,
		            height:300,
		            widthType:'%',
		            width:$('#resultTable').width(),
		            rp : 10,
		         });
		},
		queryTable: function(handleName) {
			var vehicleNo = $.trim($("#vehicleNoSelect").val());
			var alarmType = $("#alarmTypeSelect").val();
			var alarmSrc = $("#alarmSrcSelect").val();
			var inputStartDate = $("#inputStartDate").val();
			var inputEndDate = $("#inputEndDate").val();

			// 查询参数
			var params = [{
	              name: 'alarm_src',
	              value: alarmSrc
	          },{
	              name: 'vehicle_no',
	              value: vehicleNo
	          },{
	              name: 'alarm_type',
	              value: alarmType
	          },{
	              name: 'handle_name',
	              value: handleName
	          }, {
	              name: 'startTime',
	              value: inputStartDate
	          }, {
	              name: 'endTime',
	              value: inputEndDate
	          }];
			$("#resultTable").flexOptions({
				url : appCtx + "base/report/enterpriseProcessingStatistics/queryTableListByHandleName.html",
				newp : 1,// 设置起始页
				params : params
			// 设置查询参数
			}).flexReload();// 重新加载
		},
		getColumn:function(){
	    	return [{
                display : '车牌号',
                name : 'vehicle_no',
                width : 150,
                sortable : false,
                align : 'left'
            },{
                display : '报警类型',
                name : 'alarm_name',
                width : 170,
                sortable : false,
                align : 'left',
                showTitle : 'alarm_name'
            },{
                display : '报警来源',
                name : 'alarm_src',
                width : 100,
                sortable : false,
                align : 'left'
            },{
                display : '报警时间',
                name : 'alarm_time',
                width : 200,
                sortable : false,
                align : 'left'
            },{
                display : '处理类型',
                name : 'handle_type',
                width : 100,
                sortable : false,
                align : 'left'
            },{
                display : '处理时间',
                name : 'handle_time',
                width : 200,
                sortable : false,
                align : 'left'
            },{
                display : '处理内容',
                name : 'handle_remark',
                width : 150,
                sortable : false,
                align : 'left'
            }]
	    },
		getFormatTime : function (msg){
			var outTime = "0";
			if (null != msg && undefined != msg ) {
				var date = new Date(parseInt(msg)); 
				var y = date.getFullYear();    
				var m = date.getMonth() + 1;    
				m = m < 10 ? ('0' + m) : m;    
				var d = date.getDate();    
				d = d < 10 ? ('0' + d) : d;    
				var h = date.getHours();  
				h = h < 10 ? ('0' + h) : h;  
				var minute = date.getMinutes();  
				var second = date.getSeconds();  
				minute = minute < 10 ? ('0' + minute) : minute;    
				second = second < 10 ? ('0' + second) : second;   
				outTime = y + '-' + m + '-' + d+'  '+h+':'+minute+':'+second;
			}
			return outTime;
		},
		initQueryTime:function(){//默认时间
				/** 初始化日期 * */
		      var date = new Date();
		      var beforeDate=new Date(date.getTime()-3600*24000*30);
		      $("#inputStartDate").val(global.getToday(beforeDate));
		      $("#inputEndDate").val(global.getTime(date));
	      },
	      initEmptyVehicleList: function(){
		    	$("#vehicleNoSelect").select2({
			        theme: "default",
			        allowClear: true,
			        placeholder: "请选择车辆",
			        ajax:{
			            url:appCtx + "/system/common/selectVehicle.html",
			            dataType:"json",
			            delay:250,
			            data:function(params){
			                return {
			                    name: params.term,
			                    page: params.page || 1
			                };
			            },
			            cache:true,
			            processResults: function (res, params) {
					    	if(res){
					    		var options = [];
					    		var option = {"id":" ", "text":"请选择车牌号码"};
					    		options.push(option);
			    				$.each(res,function(index,obj) {
			    					var option = {"id":obj.vehicle_no, "text":obj.vehicle_no};
		    	                    options.push(option);
			    				});
		    	                return {
		    	                	results: options,
		    	                    pagination: {
		    	                        more:false
		    	                    }
		    	                };
					    	}
			            },
			            escapeMarkup: function (markup) { return markup; },
			            minimumInputLength: 1
			        }
			    });
		    },
		initBarChart : function(){
			var me = this;
			var option = {
					title : {
				        text: '人员处警统计',
				        x:'center',
				        textStyle:{
				        	fontWeight:"normal",
				        	fontSize:16
				        }
				    },
					color: ['#3398DB'],
				    tooltip : {
				        trigger: 'axis',
				        show: true,
				        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
				        	show: false,
				            type : 'line'        // 默认为直线，可选为：'line' | 'shadow'
				        },
				        formatter:function(a){
				        	if(a[0].name==''){
				        		return;
				        	}
				        	var relVal = "";
				        	relVal = a[0].name+"："+a[0].value+"次";
				        	return relVal;
				        }
				    },
				    grid: {
				        left: '3%',
				        right: '4%',
				        top:"12%",
				        bottom:"3%",
				        containLabel: true
				    },
				    xAxis : [
				        {
				            type : 'category',
				            data : [],//['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
				            axisTick: {
				                alignWithLabel: true
				            },
				            axisLabel:{
				            	
				            	textStyle: {
		                            fontSize: 12
		                        }
				            }
				        }
				    ],
				    yAxis : [
				        {
				        	type : 'value',
				        	min: 0,
					    	minInterval: 1,
					    	axisLabel: {
			                      formatter: function (value, index) {
			                    	  if (value >= 1 || value == 0) {
			                            	if (value%1 === 0) {
			                            		return value;
			                            	}
			                            }
			                        }
			                 },
				            name: '单位：次'
				        }
				    ],
				    series : [
				        {
				            name:'',
				            type:'bar',
				            barMaxWidth: '40px',
				            label:{
				            	normal:{
				            		show:true,
					            	position:"top",
					            	formatter:'{c}'
				            	}
				            	
				            },
				            itemStyle: {
				            	 label : {
				            		 normal: {
				            			 show: true, position: 'insideTop' //柱状图顶部显示数字
				            		 }
				                }
				            },
				            data:[],//[10, 52, 200, 334, 390, 330, 220]
				        }
				    ]
			};
	        
	        var myChart = echarts.init(document.getElementById('barChart'));
            myChart.setOption(option);
            window.onresize = myChart.resize;
            
            myChart.on('click', function(param){
            	var xAxisData = me.xAxisData;
            	var handleName = xAxisData[param.dataIndex];
            	$('#handle_name').val(handleName);
            	me.queryLineListByHandleName(handleName);
            	me.queryTable(handleName);
            });
            
            return {
            	refash : function(option){
                    myChart.setOption(option);
            	},
            	option : option,
            	barChartDom : myChart
            };
	        
		},
			
			initPieChart: function(){
				var me = this;
				option = {
						tooltip : {
					        trigger: 'item',
					        formatter: "{a} <br/>{b} : {c} ({d}%)"
					    },
					    legend: {
					        orient: 'vertical',
					        right:"20%",
					        top:"middle",
					        data: []//'直接访问','邮件营销','联盟广告','视频广告','搜索引擎'
					    },
					    series : [
					        {
					            name: '',
					            type: 'pie',
					            radius : '80%',
					            center: ['40%', '50%'],
					            data:[
					               /* {value:335, name:'直接访问'},
					                {value:310, name:'邮件营销'},
					                {value:234, name:'联盟广告'},
					                {value:135, name:'视频广告'},
					                {value:1548, name:'搜索引擎'}*/
					            ],
					            labelLine: {
					                normal: {
					                    show: false
					                }
					            },
					            label:{
					            	normal: {
					                    show: false
					                }
					            },
					            itemStyle: {
					            }
					        }
					    ],
					    color: ['rgb(249,124,37)','rgb(74,178,191)','rgb(134,218,179)','rgb(97,160,168)']
					};
				 var PieChart = echarts.init(document.getElementById('pieChart'));
				 PieChart.setOption(option);
		         window.onresize = PieChart.resize;
		         return {
		         	refash : function(option){
		         		PieChart.setOption(option);
		         	},
		         	option : option,
		         	pieChartDom : PieChart
		         };
			},
			initLineChart: function(){
				var me = this;
				option = {
						title : {
					        text: '处警日期分布',
					        x:'center',
					        textStyle:{
					        	fontWeight:"normal",
					        	fontSize:16
					        }
					    },
					    grid: {
					        left: '3%',
					        right: '4%',
					        top:"12%",
					        bottom:"3%",
					        containLabel: true
					    },
						tooltip: {
					        trigger: 'axis',
					        formatter:function(a){
					        	if(a[0].name==''){
					        		return;
					        	}
					        	var relVal = "";
					        	relVal = a[0].name+"："+a[0].value+"次";
					        	return relVal;
					        }
					    },
					    xAxis: {
					        type: 'category',
					        boundaryGap: false,
					        data: []
					    },
					    yAxis: {
					    	type : 'value',
					    	min: 0,
					    	minInterval: 1,
					    	axisLabel: {
			                      formatter: function (value, index) {
			                    	  if (value >= 1 || value == 0) {
			                            	if (value%1 === 0) {
			                            		return value;
			                            	}
			                            }
			                        }
			                 },
				            name: '单位：次'
					    },
					    
					    series: [{
					        data: [],
					        type: 'line',
					        
					        lineStyle:{
					        	color:"#2a5ab1"
					        },
					        
					        areaStyle: {normal: {color:"#2a5ab1"}}
					    }]
				};
				var LineChart = echarts.init(document.getElementById('lineChart'));
				LineChart.setOption(option);
				window.onresize = LineChart.resize;
				return {
					refash : function(option){
						LineChart.setOption(option);
					},
					option : option,
					lineChartDom : LineChart
				};
			},
			initProcessingStatistics: function(){
				var me=this;
				var vehicleNo = $.trim($("#vehicleNoSelect").val());
				var alarmType = $("#alarmTypeSelect").val();
				var alarmSrc = $("#alarmSrcSelect").val();
				var startTime = $("#inputStartDate").val();
				var endTime = $("#inputEndDate").val();
				
				var sta_date = new Date(startTime);
	            var end_date = new Date(endTime);//将字符串转化为时间
	            var num = (end_date - sta_date) / (1000 * 3600 * 24);//求出两个时间的时间差，这个是天数
	            var days = parseInt(Math.ceil(num));//转化为整天（小于零的话剧不用转了）
	            if(num<0){
	        		global.ajaxLoading.pop("查询开始时间不能晚于结束时间",false,2000);
	        		return;
	        	}
	            if (end_date.getMonth()-sta_date.getMonth()>1) {
	            	global.ajaxLoading.pop("查询时间不能超过一个月",false,2000);
	                return;
				}
	            if (days > 31) {
	                global.ajaxLoading.pop("查询时间不能超过一个月", false, 2000);
	                return;
	            }
				$.ajax({
					url:appCtx+"base/report/enterpriseProcessingStatistics/queryProcessingStatistics.html",
					type:"post",
					async : true,
					cache : false,
					data:{
						alarm_src:alarmSrc,
						vehicle_no:vehicleNo,
						alarm_type:alarmType,
						startTime:startTime,
						endTime:endTime
					},
					dataType:"json",
					success:function(data){
						var personnelData=data.personnelList;
							/*初始化条形图*/
							var xis = new Array();
							var series = new  Array();
							$.each(personnelData,function(index,vo){
								xis.push(vo.handle_name);
								series.push(vo.count);
							});
							var options = me.BarChart.option;
							me.xAxisData=xis;
							options.xAxis[0].data=xis;
							options.series[0].data=series;
							me.BarChart.refash(options);
							if (xis&&xis.length>0) {
								var handleName = xis[0];
				            	$('#handle_name').val(handleName);
				            	me.queryLineListByHandleName(handleName);
				            	me.queryTable(handleName);
							}else{
								var options = me.LineChart.option;
								options.xAxis.data=["-"];
								options.series[0].data=[0];
								me.LineChart.refash(options);
								var dataRows= {
	        			     		rows:[],
	        			     		total:0,
	        			     		page:1
		        			    };
								$("#resultTable").flexAddData(dataRows);
							}
			            	
							/*初始化圆形*/
							var nameArr = new Array();
							var datas = new  Array();
							$.each(data.typeList,function(index,vo){
								var handle_type=vo.handle_type==1?'系统处理':'人工处理';
								nameArr.push(handle_type);
								var map={
										name:handle_type,
										value:vo.count
									};
								datas.push(map);
							});
							var pieOptions=me.PieChart.option;
							pieOptions.legend.data=nameArr;
							pieOptions.series[0].data=datas;
							me.PieChart.refash(pieOptions);
					}
				});
			},
			queryLineListByHandleName: function(handleName){
				var me=this;
				var vehicleNo = $.trim($("#vehicleNoSelect").val());
				var alarmType = $("#alarmTypeSelect").val();
				var alarmSrc = $("#alarmSrcSelect").val();
				var inputStartDate = $("#inputStartDate").val();
				var inputEndDate = $("#inputEndDate").val();
				$.ajax({
					url:appCtx+"base/report/enterpriseProcessingStatistics/queryLineListByHandleName.html",
					type:"post",
					async : true,
					cache : false,
					data:{
						alarm_src:alarmSrc,
						vehicle_no:vehicleNo,
						alarm_type:alarmType,
						startTime:inputStartDate,
						endTime:inputEndDate,
						handle_name:handleName
					},
					dataType:"json",
					success:function(data){
						/*初始化折线图*/
						var xis = new Array();
						var series = new  Array();
						$.each(data,function(index,vo){
							var handle_time=vo.handle_time.split("-")[1]+"月"+vo.handle_time.split("-")[2]+"日";
							xis.push(handle_time);
							series.push(vo.count);
						});
						var options = me.LineChart.option;
						options.xAxis.data=xis;
						options.series[0].data=series;
						me.LineChart.refash(options);
						
					}
				});
			},
			exportComfirm:function(){
				var me = this;
				var options = $("#resultTable").getOptions();
				//总记录数
				var total = options.total;
				//开始页数
				var StartPage=window.parent.$("#StartPageIndex").val();
				//结束页数
				var EndPage=window.parent.$("#EndPageIndex").val();
				
				var validate=true;
				var msg="";
				if(!StartPage || StartPage==0){
					msg+="起始页不能为空或者0";
					validate=false;
				}
				if(!EndPage || EndPage==0){
					msg+="结束页不能为空或者0";
					validate=false;
				}
				
				if(StartPage && EndPage &&EndPage<StartPage){
					msg+="结束页要大于起始页";
					validate=false;
				}
				if(!validate){
					window.parent.global.ajaxLoading.pop(msg,false,2000);
					return;
				}
				//每页大小
				var pagesize = options.rp;
				window.parent.global.ajaxLoading.pop("正在导出,请稍后.....",true,2000);
				$('#exportModal').modal('hide');
				//获取导出的参数
				var exportParams = options.exportParams;
				if((EndPage - StartPage + 1) * pagesize > 60000&&total>60000)
				{
					global.ajaxLoading.pop("最多只能导出60000条数据", true, 2000);
					return
				}
				
				var header1 = JSON.stringify(enterpriseProcessingStatistics.getColumn());
				var colModelList=new Array();//表头
				colModelList.push(header1);
				var colModel= $.toJSON(colModelList);
				
				//图片
				 var imageUrl = me.BarChart.barChartDom.getDataURL({
						type: 'png',
					    pixelRatio: 1
				}); 
				 var imageUrl2 = me.PieChart.pieChartDom.getDataURL({
						type: 'png',
					    pixelRatio: 1
				}); 
				 var imageUrl3 = me.LineChart.lineChartDom.getDataURL({
					 type: 'png',
					 pixelRatio: 1
				 }); 
				var imgsrcList=new Array();
				imgsrcList.push(imageUrl);
				imgsrcList.push(imageUrl2);
				imgsrcList.push(imageUrl3);
				var imgsrc= $.toJSON(imgsrcList);
				
				var vehicleNo = $.trim($("#vehicleNoSelect").val());
				var alarmType = $("#alarmTypeSelect").val();
				var alarmSrc = $("#alarmSrcSelect").val();
				var inputStartDate = $("#inputStartDate").val();
				var inputEndDate = $("#inputEndDate").val();
				var handleName=$('#handle_name').val();
				var paramsGrid =  {
						colModel:colModel,
						title:"处理情况统计-企业",
						alarm_src:alarmSrc,
						vehicle_no:vehicleNo,
						alarm_type:alarmType,
						startTime:inputStartDate,
						endTime:inputEndDate,
						handle_name:handleName,
						imgsrc:imgsrc,
						StartPage:StartPage,
						EndPage:EndPage,
						PageSize:pagesize
				};
				
				post(appCtx + "base/report/enterpriseProcessingStatistics/exportEnterpriseProcessingStatistics.html",paramsGrid);
				
			},
			/**
			 * 导出
			 */
			exportEnterprise: function(){
				var options = $("#resultTable").getOptions();
				var total = options.total;
				var pages = options.pages;
				if(total==0 || pages==undefined){
					global.ajaxLoading.pop("无导出数据",true,1000);
					return;
				}
				//设置默认的开始结束页
				$("#StartPageIndex").val(1);
				$("#EndPageIndex").val(pages);
				$("#exportModal").modal('show');
			},
};
enterpriseProcessingStatistics.init();